import { login, logout } from '@/api/user' //api接口
import { getMenu } from '@/api/menu' //api接口
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    employeeCode: '', //创建人编号
    isLogin: false, //
    menuList: [] //菜单列表
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  //设置token
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_MENU: (state, value) => {
    state.menuList = value
  },
  //设置用户昵称
  SET_NAME: (state, name) => {
    state.name = name
  },

  //设置用户头像
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  isLogin: (state, isLogin) => {
    state.isLogin = isLogin
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      login(userInfo)
        .then((response) => {
          if(response.code == '-1'){
            console.log('密码错误');
            let cont = Number(localStorage.getItem('wrongPawd'))
            // let cont = 0
            cont = cont + 1
            localStorage.setItem('wrongPawd', cont)
            if(cont >= 2){
              localStorage.setItem('endTime', Number(new Date().getTime() + 300 * 1000))
            }
            // console.log(localStorage.getItem('wrongPawd'))
          }else{
            console.log('密码正确');
            localStorage.setItem('wrongPawd', 0)
          }
          const { data } = response

          console.log(data)

          commit('SET_TOKEN', data.token)
          setToken(data.token) //设置缓存
          sessionStorage.setItem('userInfo', JSON.stringify(data))
          commit('isLogin', true)
          // window.localStorage.setItem("loginTime", Date.parse(new Date()));
          getMenu().then((res) => {
            sessionStorage.setItem('menuList', JSON.stringify(res.data))
            commit('SET_MENU', res.data)
            // console.log('看看', state.menuList);
          })
          resolve(data)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // 退出登录
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      console.log('删除')
      removeToken() // must remove  token  first

      commit('isLogin', false)

      commit('RESET_STATE')
      sessionStorage.removeItem('userInfo')
      resolve()
    })
  },

  // 是否已读
  isLogin({ commit }, isLogin) {
    commit('isLogin', isLogin)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
